package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加购物车
     * @param id
     * @param num
     */
    @Override
    public void add(Long id, Integer num,String username) {
        //如果添加的商品数量小于等于0，则清空购物车
        if (num<=0){
            redisTemplate.boundHashOps("Cart_"+username).delete(id);
            //再判断此时购物车是否为空
            Long size = redisTemplate.boundHashOps("Cart_" + username).size();
            if (size == 0){
                redisTemplate.delete("Cart_" + username);
            }
            return;
        }
        //查询商品的详细信息
        //查询sku
        Result<Sku> skuResult = skuFeign.findById(id);
        Sku sku = skuResult.getData();
        //查询spu
        Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());
        Spu spu = spuResult.getData();
        //封装成orderItem
        OrderItem orderItem = CreatOrderItem(id, num, sku, spu);
        //存储到redis中
        redisTemplate.boundHashOps("Cart_"+username).put(id,orderItem);
    }

    /**
     * 查询购物车
     * @param username
     * @return
     */
    @Override
    public List<OrderItem> list(String username) {
        return redisTemplate.boundHashOps("Cart_"+username).values();
    }

    private OrderItem CreatOrderItem(Long id, Integer num, Sku sku, Spu spu) {
        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        orderItem.setId(id.toString());
        orderItem.setSpuId(spu.getId());
        orderItem.setImage(sku.getImage());
        orderItem.setName(sku.getName());
        orderItem.setNum(num);
        orderItem.setPrice(sku.getPrice());
        orderItem.setMoney(num*sku.getPrice());
        orderItem.setWeight(sku.getWeight());
        orderItem.setPayMoney(num*sku.getPrice());
        return orderItem;
    }
}
